<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
// import { useRouter } from 'vue-router'
import {
  queryUserPageList,
  addUser,
  updateUser,
  deleteUser,
  updateUserStatus,
  assignRoles
} from '@/apis/UserListApi'

import { queryRolePageList } from '@/apis/roleAPI'

// const router = useRouter()


// 查询参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 5,
  userName: '',
  type: '',
  status: '',
  startDate: '', // 添加开始日期
  endDate: ''    // 添加结束日期
})

// 用户列表数据
const userList = ref([])
const total = ref(0)
const loading = ref(false)

// 分页列表
const paginatedList = computed(() => userList.value)

// 对话框状态
const dialogVisible = ref(false)
const roleDialogVisible = ref(false)
const dialogType = ref('add') // add/edit

// 用户表单数据
const userForm = reactive({
  id: '',
  userName: '',
  type: 0,
  phone: '',
  email:'',
  status: 1
})

// 角色分配相关
const selectedRole = ref('')
const roleOptions = ref([])
const currentUserId = ref('')

// 表单引用
const userFormRef = ref(null)

// 页面加载时获取用户列表
onMounted(async () => {
  await loadUserList()
})

// 加载用户列表
const loadUserList = async () => {
  loading.value = true
  try {
    // 准备查询参数
    const searchParams = {
  pageNo: queryParams.pageNo,
  pageSize: queryParams.pageSize,
  userName: queryParams.userName,
  status: queryParams.status,
  type: queryParams.type,
  startDate: queryParams.startDate, // 添加开始日期
  endDate: queryParams.endDate      // 添加结束日期
}

    const res = await queryUserPageList(searchParams)
    userList.value = res.data.records || []
    total.value = res.data.total || 0
  } catch (e) {
    ElMessage.error(e.msg || '加载用户列表失败')
  } finally {
    loading.value = false
  }
}



// 搜索
const handleSearch = () => {
  queryParams.pageNo = 1
  loadUserList()
}

// 分页大小变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  loadUserList()
}

// 页码变化
const handleCurrentChange = (val) => {
  queryParams.pageNo = val
  loadUserList()
}

// 新增用户
const handleAdd = () => {
  dialogType.value = 'add'
  // 重置表单
  Object.assign(userForm, {
    id: '',
    userName: '',
    type: 0,
    phone: '',
    address: '',
    status: 1
  })
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(userForm, {
    id: row.id,
    userName: row.userName,
    type: row.type,
    phone: row.phone,
    address: row.address,
    status: row.status
  })
  dialogVisible.value = true
}

// 保存用户
const handleSave = async () => {
  // 表单验证
  await userFormRef.value.validate()

  try {
    if (dialogType.value === 'add') {
      await addUser(userForm)
      ElMessage.success('新增成功')
    } else {
      await updateUser(userForm)
      ElMessage.success('修改成功')
    }
    dialogVisible.value = false
    loadUserList()
  } catch (e) {
    ElMessage.error(e.msg || '操作失败')
  }
}

// 状态切换
const handleStatusChange = async (row) => {
  try {
    await updateUserStatus(row.id, row.status)
    ElMessage.success('状态更新成功')
  } catch (e) {
    row.status = row.status === 1 ? 0 : 1 // 失败回滚
    ElMessage.error(e.msg || '状态更新失败')
  }
}

// 删除用户
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户【${row.userName}】吗？`,
      '确认删除',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await deleteUser(row.id)
    ElMessage.success('删除成功')
    loadUserList()
  } catch (e) {
    if (e !== 'cancel') {
      ElMessage.error(e.msg || '删除失败')
    }
  }
}

// 分配角色
const handleAssignRole = async (row) => {
  currentUserId.value = row.id
  roleDialogVisible.value = true

  try {
    // 获取所有角色
    const res = await queryRolePageList({ pageNo: 1, pageSize: 100 })
    roleOptions.value = res.data.records || []
  } catch (e) {
    ElMessage.error(e.msg || '获取角色列表失败')
  }
}

// 保存角色分配
const handleSaveRole = async () => {
  try {
    await assignRoles(currentUserId.value, selectedRole.value)
    ElMessage.success('角色分配成功')
    roleDialogVisible.value = false
  } catch (e) {
    ElMessage.error(e.msg || '角色分配失败')
  }
}

// 查看用户详情
// const toDetail = (row) => {
//   router.push({
//     path: `/userInfoDetail/${row.id}`
//   })
// }
</script>
<template>
  <div class="container">
    <div class="user-header">
      <div class="search-box">
        <el-input  v-model="queryParams.userName" placeholder="请输入用户名称搜索" clearable  style="width: 200px;"/>
        <el-select v-model="queryParams.type" placeholder="用户类型" style="margin-left: 10px; width: 150px;" clearable>
        <el-date-picker  v-model="queryParams.startDate" type="date"  placeholder="开始日期"  style="margin-left: 10px; width: 150px;" value-format="YYYY-MM-DD"/>
        <el-date-picker v-model="queryParams.endDate" type="date" placeholder="结束日期"  style="margin-left: 10px; width: 150px;"  value-format="YYYY-MM-DD"/>
          <el-option label="普通用户" :value="0" />
          <el-option label="单位/企业" :value="1" />
        </el-select>
        <el-select v-model="queryParams.status"  placeholder="状态" style="margin-left: 10px; width: 150px;" clearable>
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
        <el-button type="primary" @click="handleSearch" style="margin-left: 10px;" >搜索</el-button>
      </div>
      <el-button type="primary" @click="handleAdd" icon="Plus">新增用户</el-button>
    </div>

    <el-table :data="paginatedList"   border  style="width: 100%; margin-top: 20px;"  v-loading="loading"  >
      <el-table-column  prop="id"  label="用户ID"  width="100"  align="center"  />
      <el-table-column prop="userName" label="用户名称" width="150"  align="center"/>
      <el-table-column  prop="phone"  label="联系电话"  width="150"  align="center"  />
      <el-table-column  prop="status"  label="状态"  width="120"  align="center"  >
        <template #default="scope">
          <el-switch  v-model="scope.row.status"  :active-value="1"  :inactive-value="0"  @change="handleStatusChange(scope.row)"  />
        </template>
      </el-table-column>
      <el-table-column  prop="createTime"  label="创建时间" width="180"  align="center"  />
      <el-table-column  label="操作"  width="200"  align="center">
        <template #default="scope">
          <el-button  text  @click="handleEdit(scope.row)"> 编辑 </el-button>
          <el-button text  @click="handleAssignRole(scope.row)"  type="primary" >  分配角色  </el-button>
          <el-button  text  @click="handleDelete(scope.row)"  type="danger"  >  删除  </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination" style="margin-top: 15px; text-align: right;">
      <el-pagination
        v-model:current-page="queryParams.pageNo"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        :page-sizes="[5, 10, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog   v-model="dialogVisible" :title="dialogType === 'add' ? '新增用户' : '编辑用户'"   width="500px"  >
      <el-form  :model="userForm"   ref="userFormRef" label-width="100px" >
        <el-form-item label="用户名称"  prop="userName"  :rules="[{ required: true, message: '请输入用户名称', trigger: 'blur' }]">
          <el-input v-model="userForm.userName" />
        </el-form-item>
        <el-form-item  label="用户类型" prop="type"  :rules="[{ required: true, message: '请选择用户类型', trigger: 'change' }]"  >
          <el-select v-model="userForm.type" placeholder="请选择用户类型">
            <el-option label="普通用户" :value="0" />
            <el-option label="单位/企业" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item  label="联系电话"  prop="phone"   >
          <el-input v-model="userForm.phone" />
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="userForm.email"/>
        </el-form-item>
        <el-form-item  label="状态"  prop="status"  >
          <el-radio-group v-model="userForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button  type="primary"  @click="handleSave"  >  确认
        </el-button>
      </template>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog  v-model="roleDialogVisible"  title="分配角色"  width="500px" >
      <el-form>
        <el-form-item label="选择角色">
          <el-select v-model="selectedRole" placeholder="请选择角色" style="width: 100%">
            <el-option  v-for="role in roleOptions"  :key="role.id"  :label="role.roleName"  :value="role.id"   />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="roleDialogVisible = false">取消</el-button>
        <el-button   type="primary"  @click="handleSaveRole"  >  确认分配  </el-button>
      </template>
    </el-dialog>
  </div>
</template>



<style scoped>
.container {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 40px);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
  margin: 15px;
}

.user-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f5f5f5;
  flex-wrap: wrap;
  gap: 15px;
}

.search-box {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
  width: 100%;
  max-width: calc(100% - 120px);
}

.el-table {
  border-radius: 4px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.el-table th {
  background-color: #fafafa !important;
  font-weight: 500 !important;
}

.el-table tr:hover > td {
  background-color: #f9fafc !important;
}

.pagination {
  margin-top: 20px;
  padding-top: 10px;
  border-top: 1px solid #f5f5f5;
}

.el-button {
  transition: all 0.2s ease;
}

.el-dialog {
  border-radius: 6px;
  overflow: hidden;
}

.el-dialog__header {
  background-color: #f5f7fa;
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
}

.el-dialog__title {
  font-size: 16px;
  font-weight: 500;
}

.el-form-item {
  margin-bottom: 18px;
}

.el-tag {
  padding: 0 8px;
  height: 24px;
  line-height: 24px;
  border-radius: 4px;
}

.el-date-picker {
  --el-datepicker-input-height: 32px;
}

.title-link {
  color: #409eff;
  cursor: pointer;
  text-decoration: none;
  transition: color 0.2s;
}

.title-link:hover {
  color: #66b1ff;
  text-decoration: underline;
}

@media (max-width: 768px) {
  .search-box {
    max-width: 100%;
  }

  .user-header {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>
